package org.example.websockettest.Controller;
import org.example.websockettest.dao.Friendship;
import org.example.websockettest.param.FriendRequestForm;
import org.example.websockettest.service.impl.FriendshipServiceImpl;
import org.example.websockettest.utils.ApiResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/friends")
public class FriendshipController {

    @Autowired
    private FriendshipServiceImpl friendshipServiceImpl;
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    // 添加好友
    @CrossOrigin(origins = "*", maxAge = 3600)
    @PostMapping("/add")
    public ResponseEntity<ApiResponse<Friendship>> addFriend(@ModelAttribute FriendRequestForm form) {
        try {
            logger.info(form.getRequesterId() + " receiver " + form.getReceiverId());
            Friendship friendship = friendshipServiceImpl.addFriend(form.getRequesterId(), form.getReceiverId());
            return ResponseEntity.ok(ApiResponse.success("Friend request sent.", null));
        }
        catch (IllegalArgumentException e){
            return ResponseEntity.badRequest().body(ApiResponse.error(400, e.getMessage()));
        }
        catch (Exception e) {
            logger.error("添加好友失败" + e.getMessage());
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "添加好友失败."));
        }
    }
    // 接收好友请求
    @CrossOrigin(origins = "*", maxAge = 3600)
    @PostMapping("/accept")
    public ResponseEntity<ApiResponse<String>> acceptFriendRequest(@RequestParam Long requesterId,@RequestParam Long receiverId) {
        try {
            logger.info(requesterId+"receiver"+receiverId);
            friendshipServiceImpl.acceptFriendRequest(requesterId,receiverId);
            return ResponseEntity.ok(ApiResponse.success("接受好友成功"));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, e.getMessage()));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "添加好友失败"));
        }
    }

    // 删除好友请求
    @CrossOrigin(origins = "*", maxAge = 3600)

    @DeleteMapping("/delete")
    public ResponseEntity<ApiResponse<String>> deleteFriend(@ModelAttribute FriendRequestForm form) {
        try {
            friendshipServiceImpl.deleteFriend(form.getReceiverId(),form.getRequesterId());
            return ResponseEntity.ok(ApiResponse.success("删除好友成功"));
        }
        catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, e.getMessage()));
        }
        catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "删除好友失败"));
        }
    }

    @CrossOrigin(origins = "*", maxAge = 3600)
    @GetMapping("/searchWithStatus")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> searchUsersWithStatus(@RequestParam String query, @RequestParam Long requesterId) {
        try {
            List<Map<String, Object>> users = friendshipServiceImpl.searchUsersWithFriendshipStatus(query, requesterId);
            return ResponseEntity.ok(ApiResponse.success("用户查找成功", users));
        }
        catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, e.getMessage()));
        }
        catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "查找失败 " + e.getMessage()));
        }
    }

    @CrossOrigin(origins = "*", maxAge = 3600)
    // 获取待通过好友列表
    @GetMapping("/pending-requests")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getPendingFriendRequests(@RequestParam Long userId) {
        try {

            List<Friendship> pendingRequests = friendshipServiceImpl.findPendingFriendRequests(userId);
//            处理数据格式
            List<Map<String, Object>> simplifiedRequests = pendingRequests.stream().map(f -> {
                Map<String, Object> map = new HashMap<>();
                map.put("userId", f.getRequester().getUserId());
                map.put("username", f.getRequester().getUsername());
                map.put("createdAt", f.getCreatedAt());
                return map;
            }).collect(Collectors.toList());

            return ResponseEntity.ok(ApiResponse.success("Pending friend requests retrieved successfully.", simplifiedRequests));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "Failed to retrieve pending friend requests."));
        }
    }
    // 获取已添加好友列表
    @CrossOrigin(origins = "*", maxAge = 3600)
    @GetMapping("/getFriends")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getFriends(@RequestParam Long userId) {
        try {
            List<Map<String, Object>> friends= friendshipServiceImpl.findAcceptedFriends(userId);
            return ResponseEntity.ok(ApiResponse.success("好友列表获取成功.", friends));
        } catch (Exception e) {
            logger.error("Failed to retrieve friends list: " + e.getMessage());
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "Failed to retrieve friends list."));
        }
    }
    // 获取在线好友
    @CrossOrigin(origins = "*", maxAge = 3600)
    @GetMapping("/online-friends")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getOnlineFriends(@RequestParam Long userId) {
        try {
            List<Map<String, Object>> onlineFriends = friendshipServiceImpl.getOnlineFriends(userId);
            return ResponseEntity.ok(ApiResponse.success("Online friends retrieved successfully.", onlineFriends));
        } catch (Exception e) {
            logger.info(String.valueOf(e));
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "Failed to retrieve online friends."));
        }
    }
}
